package com.byinsight.web.actions.util;

import java.util.Date;
import java.util.List;

import com.byinsight.web.actions.Constants;

import eg.backend.domain.Dimension;
import eg.backend.domain.fly.AggregatedRecord;
import eg.backend.util.StringUtil;

public class ExpenseHelper {

	public static String toXml(List<com.byinsight.service.dto.Expense> expense) {
		StringBuffer rows = new StringBuffer();
		for (com.byinsight.service.dto.Expense exp : expense) {
			rows.append(toXml(exp));
		}
		String ret = getXml(Constants.DATA, rows.toString());
		return ret;
	}
	
	public static String toAggregatedXml(List<AggregatedRecord> records) {
		StringBuffer ret = new StringBuffer();
		for (AggregatedRecord record : records) {
			ret.append(toXml(record));
		}
		String xml = getXml(Constants.DATA, ret.toString());
		return xml;
	}
	
	public static StringBuffer toXml(com.byinsight.service.dto.Expense expense) {
		StringBuffer sb = new StringBuffer();
		sb.append("<" + Constants.ROW + ">");
		sb.append(getXml(Constants.FIELD_EXP_ID, "" + expense.getId()));
		sb.append(getXml(Constants.FIELD_EXP_USER, "" + expense.getOwner()));
		sb.append(getXml(Constants.FIELD_EXP_DATE, dateToString(expense.getDate())));
		sb.append(getXml(Constants.FIELD_EXP_AMOUNT, "" + expense.getAmount()));
		sb.append(getXml(Constants.FIELD_EXP_DESC, expense.getName()));
		sb.append(getXml(Constants.FIELD_EXP_TAG, expense.getTags()));
		sb.append(getXml(Constants.FIELD_EXP_MERCHANT, expense.getShopName()));
		List<Dimension> dimensions = expense.getSimpleDimensions();
		for (Dimension dim : dimensions) {
			if(dim == null)
				continue;
			sb.append(getXml(getDimensionTag(dim), "" + dim.getEncodedKey()));
		}
		sb.append(getXml(Constants.FIELD_EXP_REMARK, expense.getRemark()));
		sb.append("</" + Constants.ROW + ">");
		return sb;		
	}
	
	public static StringBuffer toXml(AggregatedRecord record) {
		StringBuffer sb = new StringBuffer();
		sb.append("<" + Constants.ROW + ">");
		sb.append(getXml(Constants.DIM_ID, "" + record.getId()));
		sb.append(getXml(Constants.DIM_NAME, record.getDisplayName()));
		sb.append(getXml(Constants.FIELD_EXP_AMOUNT, "" + record.getAmount()));
		sb.append("</" + Constants.ROW + ">");
		return sb;
	}
	
	public static String getDimensionTag(com.byinsight.service.dto.Dimension dim) {
		String id = dim.getRootDimension().getEncodedKey();
		if(StringUtil.isEmpty(id))
			id = dim.getEncodedKey();
		id = "dim_" + id;
		return id;
	}
	
	public static String getDimensionTag(Dimension dim) {
		String id = dim.getRootDimension();
		if(StringUtil.isEmpty(id))
			id = dim.getEncodedKey();
		id = "dim_" + id;
		return id;
	}
	
	private static String getXml(String tag, String value) {
		return "<" + tag + ">" + value + "</" + tag + ">";
	}
	
	private static String dateToString(Date date) {
		return DateUtil.dateToString(date);
	}
}
